﻿

CREATE proc accounting.SaveAccount
@AccountID		int,
@AccountNumber	int,
@AccountName	nvarchar(100),
@Description	nvarchar(100) = null,
@Details		nvarchar(100) = null,
@Text			nvarchar(100) = null,
@SK				bit
as
begin
	set nocount on

	declare @rc int,
			@logText nvarchar(150)

	if @AccountID = 0 and @SK != 0
	begin
		select	@AccountID = max(a.AccountID) + 1
		from	[accounting].[AccountsStructure] a
		where	a.AccountID < 10000
	end

	if @AccountID = 0 and @SK = 0
	begin
		select	@AccountID = max(a.AccountID) + 1
		from	[accounting].[AccountsStructure] a
	end


	begin tran

	begin try

		;with sel
		as
		(
			select	@AccountID		'AccountID',
					@AccountNumber	'AccountNumber',
					@AccountName	'AccountName',
					@Description	'Description',
					@Details		'Details',
					@Text			'Text'
		)
		merge into [accounting].[AccountsStructure] t
		using sel s on
			s.AccountID = t.AccountID
				and s.AccountNumber = t.AccountNumber
		when not matched then
		insert (
				AccountID, 
				AccountNumber, 
				AccountName, 
				[Description], 
				[Details], 
				[Text]
				)
		values (
				s.AccountID, 
				s.AccountNumber, 
				s.AccountName, 
				s.[Description], 
				s.[Details], 
				s.[Text]
				)
		when matched then
		update
			set
				AccountID		= s.AccountID, 
				AccountNumber	= s.AccountNumber, 
				AccountName		= s.AccountName, 
				[Description]	= s.[Description], 
				[Details]		= s.[Details], 
				[Text]			= s.[Text]
				;
	end try
	begin catch
		select @AccountID 'AccountID', @AccountNumber 'AccountNumber', 0 'Return', ERROR_MESSAGE() 'Error'
		goto WithError
	end catch

	select @AccountID 'AccountID', @AccountNumber 'AccountNumber', 0 'Return', null 'Error'

	commit tran
	
	return 0

WithError:
	if @@TRANCOUNT > 0
	begin
		set @logText = 'AccountID: ' + cast(@AccountID as char(10))
		exec @rc = dbo.SaveLog
			@UserID = 999, --Agent
			@LogType = 'S',
			@LogArea = 'Ac',
			@LogDetails = @logText,
			@IsError = 1
		rollback tran
	end
	return -1
end
GO


